package cn.play.cardgame;

import android.animation.ValueAnimator;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;
import com.iflytek.sunflower.FlowerCollector;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import butterknife.InjectView;
import cn.play.cardgame.base.AppActivity;
import cn.play.cardgame.base.BaseFragment;
import cn.play.cardgame.bean.HistoryItem;
import cn.play.cardgame.bean.MachineSet;
import cn.play.cardgame.bean.MesaScoreItem;
import cn.play.cardgame.bean.PaiItem;
import cn.play.cardgame.constant.Constant;
import cn.play.cardgame.constant.Constant.GAMESTATUS;
import cn.play.cardgame.data.ErrorData;
import cn.play.cardgame.data.FaPai;
import cn.play.cardgame.data.HistoryData;
import cn.play.cardgame.data.LotteryPaiData;
import cn.play.cardgame.data.MachineSetData;
import cn.play.cardgame.data.MesaScoreData;
import cn.play.cardgame.event.CallbackEvent;
import cn.play.cardgame.util.AnimationUtils;
import cn.play.cardgame.util.CryptUtils;
import cn.play.cardgame.util.FileUtils;
import cn.play.cardgame.util.LogUtil;
import cn.play.cardgame.util.SharePreferenceUtil;
import cn.play.cardgame.widget.BetPanel;
import cn.play.cardgame.widget.CountPanel;
import cn.play.cardgame.widget.FlowBottomInfoPanel;
import cn.play.cardgame.widget.FlowLayout;
import cn.play.cardgame.widget.InfoPanel;
import cn.play.cardgame.widget.ProgressPanel;
import cn.play.cardgame.widget.ResultPanel;
import cn.play.cardgame.widget.StatusPanel;
import cn.play.cardgame.widget.TopPanel;
import de.greenrobot.event.EventBus;
import okhttp3.Call;

public class MainActivity extends AppActivity {
    @InjectView(R.id.cardLayout)
    FlowLayout mCardLayout;
    @InjectView(R.id.statusPanel)
    StatusPanel mStatusPanel;
    @InjectView(R.id.result_panel)
    ResultPanel mResultPanel;
    @InjectView(R.id.infoPanel)
    InfoPanel mInfoPanel;
    @InjectView(R.id.progressPanel)
    ProgressPanel mProgressPanel;
    @InjectView(R.id.countPanel)
    CountPanel mCountPanel;
    @InjectView(R.id.betPanel)
    BetPanel mBetPanel;
    @InjectView(R.id.flowBottomInfoPanel)
    FlowBottomInfoPanel mFlowBottomInfoPanel;
    @InjectView(R.id.top_info_panel)
    TopPanel mTopPanel;
    @InjectView(R.id.floating_tips)
    ImageView mFloatingTips;
    @InjectView(R.id.mainPanel)
    LinearLayout mMainPanel;
    @InjectView(R.id.floating_text_tips)
    TextView mFloatingTxtTips;
    @InjectView(R.id.llContent)
    LinearLayout mLlContent;
    private static final int FLOWLAYOUT_CARD_CHILD_ITEM = 1;

    private WakeLock wakeLock = null;
    private MachineSet machineSet;
    private QCodeDialog qcodeDialog;
    private int mLastStatus = -1;
    // private int densityDpi = 0;
    private boolean isShowing;
    // private DisplayMetrics displayMetrics;
    private Intent mediaService;
    SoundService msgService;
    private boolean flag = true;
    private Thread mUpdateThread;
    private Handler mAnimHandler;
    private Map<Integer, String> historyMap;
    private static final String DIR = "cardgame";
    private static final String CONFIG = "config.txt";

    private final String TIME_OVER_HINT = "押注时间小于3秒，不能押注";
    SpeechSynthesizer mTts;

    int count = 0;
    private int mWidth;
    private int mHeight;

    ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            LogUtil.getLogger().d7("08221455", "------------onServiceDisconnected------------");
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //返回一个MsgService对象
            LogUtil.getLogger().d7("08221455", "------------onServiceConnected------------");
            msgService = ((SoundService.SoundBinder) service).getService();

            msgService.playSongByType(1, -1, null);
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        initIfly();
//		CrashReport.testJavaCrash();
        hideNavigationBar();
        initView();
        initData();
        initListener();
        initHandler();
    }

    private void initView() {

    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            hideNavigationBar();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        flag = true;
        wakeLock.acquire();
    }

    @Override
    protected void onPause() {
        super.onPause();
        wakeLock.release();
    }

    public void hideNavigationBar() {
        int uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN; // hide status bar

        if (android.os.Build.VERSION.SDK_INT >= 19) {
            uiFlags |= 0x00001000; // SYSTEM_UI_FLAG_IMMERSIVE_STICKY: hide
            // navigation bars - compatibility: building
            // API level is lower thatn 19, use magic
            // number directly for higher API target
            // level
        } else {
            uiFlags |= View.SYSTEM_UI_FLAG_LOW_PROFILE;
        }

        getWindow().getDecorView().setSystemUiVisibility(uiFlags);
    }

    private void initData() {
        qcodeDialog = new QCodeDialog();
        historyMap = new HashMap<>();
        // 屏幕密度，分辨率
        // displayMetrics = getResources().getDisplayMetrics();
        // Log.d("Density", "Density is " + displayMetrics.density +
        // " densityDpi is " + displayMetrics.densityDpi
        // + " height: " + displayMetrics.heightPixels + " width: " +
        // displayMetrics.widthPixels);
        // Toast.makeText(this,
        // "Density is " + displayMetrics.density + " densityDpi is " +
        // displayMetrics.densityDpi + " height: "
        // + displayMetrics.heightPixels + " width: " +
        // displayMetrics.widthPixels,
        // Toast.LENGTH_SHORT).show();
        // densityDpi = displayMetrics.densityDpi;

        // 屏幕常亮
        PowerManager powerManager = (PowerManager) this.getSystemService(Service.POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "CardGameMachine");

//


        //绑定Service
        Intent intent = new Intent(MainActivity.this, SoundService.class);
        bindService(intent, conn, Context.BIND_AUTO_CREATE);


//        mediaService = new Intent(MainActivity.this, SoundService.class);
//        mediaService.putExtra("SONG", 1);
//        mediaService.putExtra("MSG", SoundService.PLAY_MSG);
//        startService(mediaService);


//        Toast.makeText(this, "机子ip:" + InterAddressUtil.getLocalIpAddress(), Toast.LENGTH_SHORT).show();

        readConfig();
//        // 打8个包，对应1-8号机台
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                Looper.prepare();
//                if (!FileUtils.isFolderExist(DIR)) {
//                    FileUtils.creatSDDir(DIR);
//                    if (!FileUtils.isFileExist(DIR, CONFIG)) {
//                        try {
//                            FileUtils.createFileInSDCard(DIR, CONFIG);
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }
//                byte[] bytes = FileUtils.readFromSD(DIR, CONFIG);
//                String config = new String(bytes);
//                String[] configs = config.split("\r\n");
//                if (configs != null && configs.length > 0) {
//                    for (int i = 0; i < configs.length; i++) {
//                        Log.d("MeasureData", configs[i]);
//                        String str = configs[i];
//                        String[] map = str.split("#");
//                        if (map != null && map.length == 2) {
//                            if (map[0].equals("POSITION")) {
//                                mBetPanel.setMachinePos(Integer.parseInt(map[1]));
//        mBetPanel.setMachinePos(1);
//                                Constant.POSITION = Integer.parseInt(map[1]);
//                            } else if (map[0].equals("IP")) {
//                                Constant.BASE_URL = map[1];
//                            }
//                        }
//                    }
//                }
//                if (!Constant.BASE_URL.equals("")) {
//        Toast.makeText(MainActivity.this, "baseurl:" + Constant.BASE_URL, Toast.LENGTH_LONG).show();
        Constant.GET_MACHINESET_BY_ID = Constant.BASE_URL + "machineset/getById";
        Constant.GET_POKER = Constant.BASE_URL + "poker/machine/getPoker";
        Constant.GET_HISTORY = Constant.BASE_URL + "poker/getHistory";
        Constant.MACHINE_UPDATE_STAKE = Constant.BASE_URL + "machine/updateStake";
        Constant.CANCEL_STAKE = Constant.BASE_URL + "machine/cancelStake";
        Constant.ADD_VALUE = Constant.BASE_URL + "machine/addValue";
        Constant.RETURN_VALUE = Constant.BASE_URL + "machine/returnValue";
        Constant.GET_MESA_SCORE = Constant.BASE_URL + "machine/getMesaScore";
        // 获取历史牌路
//        Toast.makeText(MainActivity.this, "第一个接口:" + Constant.GET_HISTORY, 1).show();
        OkHttpUtils.post().url(Constant.GET_HISTORY).addParams(Constant.KEY_MACHINE_ID, Constant.MACHINE_ID)
                .id(6).build().execute(new MyStringCallback());
//                } else {
//                    Toast.makeText(MainActivity.this, "请确认是否有配置文件", Toast.LENGTH_SHORT).show();
//                }
//                Looper.loop();
//            }
//        }).start();
        mPlayer = MediaPlayer.create(this, R.raw.diaoluo_da);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//Toast.makeText(this, "onKeyDown", Toast.LENGTH_SHORT).show();
        // 不在押分阶段按了也没用
//        if (!mBetPanel.getIsButtonHighlighted())
//            return true;
//        switch (keyCode) {
//            case KeyEvent.KEYCODE_A:
//            case KeyEvent.KEYCODE_B:
//            case KeyEvent.KEYCODE_C:
//            case KeyEvent.KEYCODE_D:
//            case KeyEvent.KEYCODE_E:
//                if (event.getRepeatCount() == 0) {
//                    event.startTracking();
//                    return true;
//                }
//                return true;
//        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        // S H C D O
        switch (keyCode) {
            case KeyEvent.KEYCODE_A:
                LogUtil.getLogger().d7("08210928", "-----onKeyUp-----KeyEvent.KEYCODE_A-----------");

                // 不在押分阶段按了也没用
                if (!mBetPanel.getIsButtonHighlighted())
                    return true;

                if (!mStatusPanel.isFiveTimeMillisLeft()) {
                    Toast.makeText(this, TIME_OVER_HINT, Toast.LENGTH_SHORT).show();
                    return true;
                }
//                Toast.makeText(this, "A", Toast.LENGTH_SHORT).show();
                if (mBetPanel.isLockLongPressKeyHeitao()) {
//                    Toast.makeText(this, "A long", Toast.LENGTH_SHORT).show();
                    mBetPanel.setLockLongPressKeyHeitao(false);
                    return true;
                }
                mBetPanel.addBet("S");
//                 betQueue.add("S");
                break;
            case KeyEvent.KEYCODE_B:
                LogUtil.getLogger().d7("08210928", "-----onKeyUp-----KeyEvent.KEYCODE_B-----------");
                if (!mBetPanel.getIsButtonHighlighted())
                    return true;
                if (!mStatusPanel.isFiveTimeMillisLeft()) {
                    Toast.makeText(this, TIME_OVER_HINT, Toast.LENGTH_SHORT).show();
                    return true;
                }
//                Toast.makeText(this, "B", Toast.LENGTH_SHORT).show();
                if (mBetPanel.isLockLongPressKeyHongtao()) {
                    mBetPanel.setLockLongPressKeyHongtao(false);
                    return true;
                }
                mBetPanel.addBet("H");
                // betQueue.add("H");
                break;
            case KeyEvent.KEYCODE_C:
                LogUtil.getLogger().d7("08210928", "-----onKeyUp-----KeyEvent.KEYCODE_C-----------");
                if (!mBetPanel.getIsButtonHighlighted())
                    return true;
                if (!mStatusPanel.isFiveTimeMillisLeft()) {
                    Toast.makeText(this, TIME_OVER_HINT, Toast.LENGTH_SHORT).show();
                    return true;
                }
//                Toast.makeText(this, "C", Toast.LENGTH_SHORT).show();
                if (mBetPanel.isLockLongPressKeyCaohua()) {
                    mBetPanel.setLockLongPressKeyCaohua(false);
                    return true;
                }
                mBetPanel.addBet("C");
//                 betQueue.add("C");
                break;
            case KeyEvent.KEYCODE_D:
                LogUtil.getLogger().d7("08210928", "-----onKeyUp-----KeyEvent.KEYCODE_D-----------");
                if (!mBetPanel.getIsButtonHighlighted())
                    return true;
                if (!mStatusPanel.isFiveTimeMillisLeft()) {
                    Toast.makeText(this, TIME_OVER_HINT, Toast.LENGTH_SHORT).show();
                    return true;
                }
//                Toast.makeText(this, "D", Toast.LENGTH_SHORT).show();
                if (mBetPanel.isLockLongPressKeyFangkuai()) {
                    mBetPanel.setLockLongPressKeyFangkuai(false);
                    return true;
                }
                mBetPanel.addBet("D");
                // betQueue.add("D");
                break;
            case KeyEvent.KEYCODE_E:
                LogUtil.getLogger().d7("08210928", "-----onKeyUp-----KeyEvent.KEYCODE_E-----------");
                if (!mBetPanel.getIsButtonHighlighted())
                    return true;
                if (!mStatusPanel.isFiveTimeMillisLeft()) {
                    Toast.makeText(this, TIME_OVER_HINT, Toast.LENGTH_SHORT).show();
                    return true;
                }
//                Toast.makeText(this, "E", Toast.LENGTH_SHORT).show();
                if (mBetPanel.isLockLongPressKeyKing()) {
                    mBetPanel.setLockLongPressKeyKing(false);
                    return true;
                }
                mBetPanel.addBet("O");
                // betQueue.add("O");
                break;
            case KeyEvent.KEYCODE_F: // 隐藏自己的押分
                LogUtil.getLogger().d7("08210928", "-----onKeyUp-----KeyEvent.KEYCODE_F-----------");
                //Toast.makeText(this, "隐藏自己的押分", Toast.LENGTH_SHORT).show();
                mBetPanel.setMineBetVisible();
                break;
            case KeyEvent.KEYCODE_G: // 取消本次押分
//                LogUtil.getLogger().d7("08210928", "-----onKeyUp-----KeyEvent.KEYCODE_G-----------");
//                Toast.makeText(this, "取消本次押分", Toast.LENGTH_SHORT).show();
                // 如果有押分按键一直按着，就取消不了
                if (mBetPanel.isLockLongPressKeyHeitao() || mBetPanel.isLockLongPressKeyHongtao()
                        || mBetPanel.isLockLongPressKeyCaohua() || mBetPanel.isLockLongPressKeyFangkuai()
                        || mBetPanel.isLockLongPressKeyKing())
                    return true;
                EventBus.getDefault().post(new CallbackEvent(Constant.EVENT_NOTIFY_CANCEL_CURRENT_MINE_BET, ""));
                break;
            case KeyEvent.KEYCODE_H: // 二维码
                LogUtil.getLogger().d7("08210928", "-----onKeyUp-----KeyEvent.KEYCODE_H-----------");
//                Toast.makeText(this, "二维码", Toast.LENGTH_SHORT).show();
                showQCode();
                break;
            case KeyEvent.KEYCODE_I: // 上分
                LogUtil.getLogger().d7("08210928", "-----onKeyUp-----KeyEvent.KEYCODE_I-----------");
//                Toast.makeText(this, "上分", Toast.LENGTH_SHORT).show();
                mBetPanel.addValue();
                break;
            case KeyEvent.KEYCODE_J: // 下分
                LogUtil.getLogger().d7("08210928", "-----onKeyUp-----KeyEvent.KEYCODE_J-----------");
//                Toast.makeText(this, "下分", Toast.LENGTH_SHORT).show();
                mBetPanel.returnValue();
                break;
            case KeyEvent.KEYCODE_K: // 改变step
                LogUtil.getLogger().d7("08210928", "-----onKeyUp-----KeyEvent.KEYCODE_K-----------");
                mFlowBottomInfoPanel.setBetStep();
                break;
            case KeyEvent.KEYCODE_L: // 改变step
                LogUtil.getLogger().d7("08210928", "-----onKeyUp-----KeyEvent.KEYCODE_L-----------");
                mFlowBottomInfoPanel.setBetStep();
                break;
            case KeyEvent.KEYCODE_M: // 改变step
                LogUtil.getLogger().d7("08210928", "-----onKeyUp-----KeyEvent.KEYCODE_M-----------");
                mFlowBottomInfoPanel.setBetStep();
                break;
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_A:
//                Toast.makeText(this, "长按黑桃", Toast.LENGTH_SHORT).show();
                mBetPanel.setLockLongPressKeyHeitao(true);
                return true;
            case KeyEvent.KEYCODE_B:
//                Toast.makeText(this, "长按红桃", Toast.LENGTH_SHORT).show();
                mBetPanel.setLockLongPressKeyHongtao(true);
                return true;
            case KeyEvent.KEYCODE_C:
//                Toast.makeText(this, "长按草花", Toast.LENGTH_SHORT).show();
                mBetPanel.setLockLongPressKeyCaohua(true);
                return true;
            case KeyEvent.KEYCODE_D:
//                Toast.makeText(this, "长按方块", Toast.LENGTH_SHORT).show();
                mBetPanel.setLockLongPressKeyFangkuai(true);
                return true;
            case KeyEvent.KEYCODE_E:
//                Toast.makeText(this, "长按王", Toast.LENGTH_SHORT).show();
                mBetPanel.setLockLongPressKeyKing(true);
                // 执行长按动作
                return true;
        }
        return super.onKeyLongPress(keyCode, event);
    }

    private void resetView() {
        if (machineSet != null) {
            mBetPanel.setData(machineSet);

            setInfoPanel(false);

            Constant.BUREAU_MAX = machineSet.getGamesNum(); // 100
            Constant.TURN_MAX = machineSet.getTotalGameNum() / Constant.BUREAU_MAX;

            Constant.READY_MILLISEC = machineSet.getReadyTime() * 1000;
            Constant.PREPARE_MILLISEC = Constant.READY_MILLISEC;
            // Constant.PREPARE_MILLISEC = machineSet.getKickOffTime() * 1000
            // + Constant.MachineRun_MILLISEC; // 20s
            Constant.PLAY_MILLISEC = machineSet.getBetTime() * 1000; // 30s
            // Constant.LOTTERY_MILLISEC = 10 * 1000 + Constant.READY_MILLISEC
            // + Constant.MachineRun_MILLISEC; // 10s
            Constant.LOTTERY_MILLISEC = machineSet.getKickOffTime() * 1000; // 10s
            Constant.SPACE_MILLISEC = machineSet.getSpaceTime() * 1000; // 60s
            // Constant.MAX_BUREAU_LOTTERY_MILLISEC = 10 * 1000
            // + Constant.MachineRun_MILLISEC + Constant.SPACE_MILLISEC;
            Constant.KING_RATIO = Integer.parseInt(removeDot(machineSet.getKingOdds()));
            Constant.FOUR_RED_LIMIT = machineSet.getOneLimitRed();
            Constant.KING_RED_LIMIT = machineSet.getKingLimitRed();
            // mTopPanel.setFourXianhong(machineSet.getFourLimitRed());
            // mTopPanel.setKingXianhong(machineSet.getKingLimitRed());
        }
        mTopPanel.setFourXianhong(Constant.FOUR_RED_LIMIT);
        mBetPanel.setKingRatio();

        // 获取牌路状态，每秒请求一次
        if (mUpdateThread == null) {
            mUpdateThread = new Thread(new Runnable() {

                @Override
                public void run() {
                    while (true) {
                        if (flag) {
//                            LogUtil.getLogger().d("zshhh = " +"run thread");
                            OkHttpUtils.post().url(Constant.GET_POKER).addParams(Constant.KEY_MACHINE_ID, Constant.MACHINE_ID)
                                    .id(1).build().execute(new MyStringCallback());
                        }
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
            mUpdateThread.start();
        }
    }

    // 去除小数点后面的0，全为0清除小数点
    private String removeDot(String s) {
        if (s.indexOf(".") > 0) {
            // 正则表达
            s = s.replaceAll("0+?$", "");// 去掉后面无用的零
            s = s.replaceAll("[.]$", "");// 如小数点后面全是零则去掉小数点
        }
        return s;
    }

    private void resetResultPanel(int height) {
        mResultPanel.resetResultPanel(height);
    }

    private void initListener() {
        // int screenWidth = ScreenUtils.getScreenWidth(this);// 2560
        // int screenHeight = ScreenUtils.getScreenHeight(this);// 1440
        mMainPanel.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                mMainPanel.getViewTreeObserver().removeGlobalOnLayoutListener(this); // 一定要移除，否则会调用多次，造成卡顿
                // int width = mMainPanel.getMeasuredWidth(); // 1982
                int height = mMainPanel.getMeasuredHeight(); // 989
                resetResultPanel(height);
                // int resultPanelWidth = mResultPanel.getResultWidth();
                // int w = width - mResultPanel.getResultWidth()
                // - ScreenUtils.dp2px(70);
                // int cardShowSize = Constant.CARD_WIDTH * densityDpi /
                // 480;
                initCardLayout();
            }
        });
    }

    private void initHandler() {
        mAnimHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 0:
                        AnimationUtils.getInstance().setShowAnimation(mFloatingTips, 500);
                        mAnimHandler.sendEmptyMessageDelayed(1, 500);
                        break;

                    case 1:
                        AnimationUtils.getInstance().setHideAnimation(mFloatingTips, 500);
                        mAnimHandler.sendEmptyMessageDelayed(0, 500);
                        break;
                    case 2:
                        break;
                }
            }
        };
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    protected int getFragmentContentId() {
        return super.getFragmentContentId();
    }

    @Override
    protected BaseFragment getFirstFragment() {
        return null;
    }

    @Override
    public void onClick(View v) {

    }

    private void setPai(int bureau, String huase, String value) {
        int index = bureau - 1;
        FrameLayout frameLayout = (FrameLayout) mCardLayout.getChildAt(index);
        ImageView view = (ImageView) frameLayout.getChildAt(FLOWLAYOUT_CARD_CHILD_ITEM);
        view.setBackgroundResource(FaPai.getImage(this, value, huase, 2));
    }

    private void clearPai() {
        for (int i = 0; i < Constant.BUREAU_MAX; i++) {
            FrameLayout frameLayout = (FrameLayout) mCardLayout.getChildAt(i);
            ImageView view = (ImageView) frameLayout.getChildAt(FLOWLAYOUT_CARD_CHILD_ITEM);
            view.setBackgroundResource(0);
        }
    }

    @SuppressWarnings("deprecation")
    private void initCardLayout() {
        mLlContent.post(new Runnable() {
            @Override
            public void run() {
                mWidth = mLlContent.getWidth();
                mHeight = mLlContent.getHeight();
                int width = (int) (mWidth * 1.0f / 15 * 0.95);
                int height = (int) (mHeight * 1.0f / 7 * 0.94);
                for (int i = 0; i < Constant.BUREAU_MAX; i++) {
                    FrameLayout frameLayout = new FrameLayout(MainActivity.this);
                    // MarginLayoutParams params = new
                    // MarginLayoutParams(Constant.CARD_WIDTH * densityDpi / 240,
                    // Constant.CARD_HEIGHT * densityDpi / 240);
                    ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(width, height);

                    ImageView card_bg = new ImageView(MainActivity.this);
                    card_bg.setBackgroundResource(R.drawable.card_background);
                    card_bg.setScaleY(0.93f);
                    card_bg.setScaleX(0.93f);
                    frameLayout.addView(card_bg);


                    ImageView view = new ImageView(MainActivity.this);
                    view.setScaleX(0.93f);
                    view.setScaleY(0.93f);
                    frameLayout.addView(view);

                    frameLayout.setLayoutParams(params);
                    mCardLayout.addView(frameLayout);
                }
            }
        });
    }

    public void onEventMainThread(CallbackEvent event) {
        int code = event.getCode();
        String msg = event.getMsg();
        switch (code) {
            case Constant.EVENT_NOTIFY_CURRENT_MINE_BET:
                setInfoPanel(false);
                break;
            case Constant.EVENT_NOTIFY_CANCEL_CURRENT_MINE_BET:
                // 押注状态下倒数5秒不可取消
                if (mStatusPanel.getCurrentStatus() == GAMESTATUS.GAME_PLAY) {
                    if (mStatusPanel.isFiveTimeMillisLeft()) {
                        mBetPanel.cancelBet();
                    } else {
                        Toast.makeText(this, "押注时间小于5秒，不能取消", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            case Constant.EVENT_NOTIFY_PREPARE_TO_BET:
                if (mStatusPanel.getCurrentStatus() == GAMESTATUS.GAME_PLAY) {
                    if (mStatusPanel.isFiveTimeMillisLeft()) {
                        mBetPanel.addBet(msg);
                    } else {
                        Toast.makeText(this, TIME_OVER_HINT, Toast.LENGTH_LONG).show();
                    }
                }
                break;
            case Constant.EVENT_NOTIFY_CAMERA_BOTTOM_STATUS:
                mStatusPanel.setCameraStatus(msg);
                break;
            case Constant.EVENT_NOTIFY_BET:
                if (msg.equals("2")) // play
                    mBetPanel.setButtonEnabled(true);
                else
                    mBetPanel.setButtonEnabled(false);
                break;
            case Constant.EVENT_NOTIFY_CHANGE_BET_STEP:
                mBetPanel.changeStep(Integer.parseInt(msg));
                break;
            case Constant.EVENT_NOTIFY_SHOW_TIPS:
                mFloatingTips.setVisibility(View.VISIBLE);
                mFloatingTips.setBackgroundResource(R.drawable.begin_bet);
                mAnimHandler.sendEmptyMessage(0);
                break;
            case Constant.EVENT_NOTIFY_HIDE_TIPS:
                mFloatingTips.setVisibility(View.GONE);
                mFloatingTips.setBackgroundResource(0);
                mAnimHandler.removeMessages(0);
                mAnimHandler.removeMessages(1);
                break;
            case Constant.EVENT_NOTIFY_HAS_REACH_MAX_TURN:
                // 注意添加动画，暂时不加
                mFloatingTxtTips.setText("请联系工作人员进行解锁");
                mFloatingTxtTips.setVisibility(View.VISIBLE);
                // 一直发送请求直到解锁为止，则隐藏字样
                break;
        }
    }

    private void showQCode() {
        // show了之后才会调用onCreateDialog和onStart,否则没有show的情况下调用dialog.getDialog()会返回null
        isShowing = !isShowing;
        if (isShowing) {
            // qcodeDialog.show(getFragmentManager(), "qCodeDialog");
            // getFragmentManager().beginTransaction().show(qcodeDialog).commit();
//            Toast.makeText(this, "show", Toast.LENGTH_SHORT).show();
            qcodeDialog.show(getFragmentManager(), "qCodeDialog");
        } else {
//            Toast.makeText(this, "hide", Toast.LENGTH_SHORT).show();
            qcodeDialog.dismiss();
            // Toast.makeText(this, "dismiss", Toast.LENGTH_SHORT).show();
            // // qcodeDialog.dismiss();
            // getFragmentManager().beginTransaction().hide(qcodeDialog).commit();
        }

    }

    private void setInfoPanel(boolean isLorry) {
        LogUtil.getLogger().d2("mBetPanel.getBalance() = " + mBetPanel.getBalance() + "mBetPanel.getMineBetAll() = "
                + mBetPanel.getMineBetAll() + "mBetPanel.getAppCurrentProfit() = " + mBetPanel.getAppCurrentProfit());
        mInfoPanel.setWin(mBetPanel.getAppCurrentProfit());
        if (isLorry) {
            mAnimHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    handleBalance();
                    handleWin();
                }
            },8000);
        } else {
            mInfoPanel.setBalance(mBetPanel.getBalance());
            mInfoPanel.setWin(mBetPanel.getAppCurrentProfit());
        }
        mInfoPanel.setBet(mBetPanel.getMineBetAll());
        mInfoPanel.setLastWin(SharePreferenceUtil.getLastWin(this));

//        mInfoPanel.setBalance(mBetPanel.getBalance());
//        mInfoPanel.setBet(5);
//        mInfoPanel.setWin(5);
//        mInfoPanel.setLastWin(5);
    }

    private MediaPlayer mPlayer;
    private float currentBalance = 0;
    public static final int DURATION = 2000;


    private void handleBalance() {
        if (currentBalance != mBetPanel.getBalance() && mBetPanel.getBalance() != 0) {
            currentBalance = mBetPanel.getBalance();
            ValueAnimator valueAnimator = ValueAnimator.ofFloat(mInfoPanel.getBalance(), mBetPanel.getBalance());
            valueAnimator.setDuration(DURATION);

            valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator valueAnimator) {
                    mInfoPanel.setBalance((Float) valueAnimator.getAnimatedValue());
                }
            });
            valueAnimator.start();
        }
    }

    private void handleWin() {
        if (mPlayer != null && mBetPanel.getAppCurrentProfit() != 0) {
            try {
                mPlayer.start();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            }
        }
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(mBetPanel.getAppCurrentProfit(), 0);
        valueAnimator.setDuration(DURATION);

        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                mInfoPanel.setWin((Float) valueAnimator.getAnimatedValue());
            }
        });
        valueAnimator.start();


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaService != null)
            stopService(mediaService);

        if (mAnimHandler != null) {
            mAnimHandler.removeMessages(0);
            mAnimHandler.removeMessages(1);
        }
        mStatusPanel.cancel();
        flag = false;
        EventBus.getDefault().unregister(this);
    }

    private void updateUI(PaiItem paiItem) {
        LogUtil.getLogger().d7("myTime", "mLastStatus = " + mLastStatus + "--paiItem.getStatus() = " + paiItem.getStatus());
        if (paiItem.getStatus() == 0)
            return;
        if (mLastStatus != paiItem.getStatus()) {
            mLastStatus = paiItem.getStatus();
            mProgressPanel.setTurn(paiItem.getRounds());
            mProgressPanel.setBureau(paiItem.getBouts());
            String updateTime = paiItem.getUpdateTime();
            String currentTime = paiItem.getCurrentTime();

            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            long diff = 0;
            try {
                Date curuentDate = df.parse(currentTime);
                Date updateDate = df.parse(updateTime);
                diff = curuentDate.getTime() - updateDate.getTime();// 这样得到的差值是微秒级别

            } catch (ParseException e) {
                e.printStackTrace();
            }

            if (paiItem.getStatus() == 1) { // 初始化 readyTime
                setCountPanel();
                mBetPanel.cleanSendMap();
                mStatusPanel.switchStatus(GAMESTATUS.GAME_PREPARE);
                mStatusPanel.setMillisInFuture(Constant.PREPARE_MILLISEC - diff);
                setNewBureauInfo();
                LogUtil.getLogger().d7("07281647", "mLastStatus = " + mLastStatus + "--updateTime = " + updateTime + "--currentTime = " + currentTime + "------diff=" + diff + "----Constant.PREPARE_MILLISEC=" + Constant.PREPARE_MILLISEC);
            } else if (paiItem.getStatus() == 2) { // 押分 bettime
                setCountPanel();
                if (diff < 2000) // 2s内提示声音
                    msgService.playSongByType(1, 0, "youxi_kaisi");
                mStatusPanel.switchStatus(GAMESTATUS.GAME_PLAY);
                mStatusPanel.setMillisInFuture(Constant.PLAY_MILLISEC - diff);
                LogUtil.getLogger().d7("07281647", "mLastStatus = " + mLastStatus + "--updateTime = " + updateTime + "--currentTime = " + currentTime + "------diff=" + diff + "----Constant.PLAY_MILLISEC=" + Constant.PLAY_MILLISEC);
                // 换成美女图
                mResultPanel.setRandomBeatuBackground();
            } else if (paiItem.getStatus() == 4) { // 开奖kickofftime
                // 声音
                mBetPanel.cleanSendMap();
                if (diff < 2000) // 2s内提示声音
                {
//                    SoundUtils.getInstance().generateAudio(this,
//                            SoundUtils.getInstance().generateVoiceText(paiItem.getPaiHuase(), paiItem.getPaiIndex()));
                    msgService.playSongByType(1, paiItem.getPaiIndex(), paiItem.getPaiHuase());
                }
                mStatusPanel.switchStatus(GAMESTATUS.GAME_LOTTERY);
                if (mProgressPanel.getBureau() == Constant.BUREAU_MAX) {
                    mStatusPanel.setMillisInFuture(Constant.LOTTERY_MILLISEC - diff);
                    LogUtil.getLogger().d7("07281647", "mLastStatus = " + mLastStatus + "--updateTime = " + updateTime + "--currentTime = " + currentTime + "------diff=" + diff + "----Constant.LOTTERY_MILLISEC=" + Constant.LOTTERY_MILLISEC);
                    // mStatusPanel.setMillisInFuture(Constant.LOTTERY_MILLISEC
                    // - diff - Constant.READY_MILLISEC
                    // + Constant.SPACE_MILLISEC);
                } else {
                    mStatusPanel.setMillisInFuture(Constant.LOTTERY_MILLISEC - diff);
                    LogUtil.getLogger().d7("07281647", "mLastStatus = " + mLastStatus + "--updateTime = " + updateTime + "--currentTime = " + currentTime + "------diff=" + diff + "----Constant.LOTTERY_MILLISEC=" + Constant.LOTTERY_MILLISEC);
                }
                lottery(paiItem);
            } else if (paiItem.getStatus() == 3) {
                mBetPanel.cleanSendMap();
                mStatusPanel.switchStatus(GAMESTATUS.GAME_PAUSE);
                mStatusPanel.setMillisInFuture(5);
            }
            mStatusPanel.start();
        }
    }

    private void setNewBureauInfo() {
        // 新的一局需要将上次BetPanel里的押注清零
        mBetPanel.clearMineBet();
        // 新的一局需要将上次InfoPanel里的信息清零
        setInfoPanel(false);
        // 新的一局开始需要将ResultPanel中背景切换回默认
        mResultPanel.setDefaultBackground();
        if (mProgressPanel.getBureau() == 1) {
            clearPai();
            historyMap.clear();
            // 新的一轮需要将CountPanel中数据清零
            mCountPanel.reset();
        }
    }

    private void lottery(PaiItem paiItem) {
        // 更新开奖结果
        mResultPanel.setLottery(paiItem.getPaiValue(), paiItem.getPaiHuase());
        // 将中奖花色在BetPanel中高亮显示
        mBetPanel.setHighLight(paiItem);
        // 计算收益与亏损
        setInfoPanel(true);
        SharePreferenceUtil.putLastWin(this, mBetPanel.getAppCurrentProfit());
        // 历史牌里显示
        setPai(mProgressPanel.getBureau(), paiItem.getPaiHuase(), paiItem.getPaiValue());
        // count各花色数量
        if (!historyMap.containsKey(mProgressPanel.getBureau())) {
            historyMap.put(mProgressPanel.getBureau(), paiItem.getPaiHuase());
        }
        setCountPanel();
    }

    private void setCountPanel() {
        int historyHeixinCount = 0;
        int historyHongxinCount = 0;
        int historyCaohuaCount = 0;
        int historyFangkuaiCount = 0;
        int historyKingCount = 0;

        for (Entry<Integer, String> entry : historyMap.entrySet()) {
            String value = entry.getValue();
            if (FaPai.isHeixin(value)) {
                historyHeixinCount++;
            } else if (FaPai.isHongxin(value)) {
                historyHongxinCount++;
            } else if (FaPai.isFangkuai(value)) {
                historyFangkuaiCount++;
            } else if (FaPai.isCaohua(value)) {
                historyCaohuaCount++;
            } else if (FaPai.isKing(value)) {
                historyKingCount++;
            }
        }

        mCountPanel.setHeixinCount(historyHeixinCount);
        mCountPanel.setHongxinCount(historyHongxinCount);
        mCountPanel.setCaohuaCount(historyCaohuaCount);
        mCountPanel.setFangkuaiCount(historyFangkuaiCount);
        mCountPanel.setKingCount(historyKingCount);
    }

    private void updateUponHistory(HistoryItem historyItem) {
        int turn = historyItem.getCurrentPoker().getRounds();
        int bureau = historyItem.getCurrentPoker().getBouts();

        mProgressPanel.setTurn(turn);
        mProgressPanel.setBureau(bureau);

        historyMap.clear();
        for (PaiItem paiItem : historyItem.getHistoryList()) {
            setPai(paiItem.getBouts(), paiItem.getPaiHuase(), paiItem.getPaiValue());
            String color = paiItem.getPaiHuase();
            historyMap.put(paiItem.getBouts(), color);
        }
    }

    public class MyStringCallback extends StringCallback {

        @Override
        public void onError(Call call, Exception e, int id) {
//            Toast.makeText(MainActivity.this, "MyStringCallback   -------      onError    id=" + id, Toast.LENGTH_LONG).show();
            e.printStackTrace();
            if (id == 6) {
//                Toast.makeText(MainActivity.this, "history fail", Toast.LENGTH_LONG).show();
            } else if (id == 3) {
//                Toast.makeText(MainActivity.this, "machineset fail", Toast.LENGTH_LONG).show();
            } else if (id == 5) {
//                Toast.makeText(MainActivity.this, "measure fail", Toast.LENGTH_LONG).show();
            } else if (id == 1) {
//                LogUtil.getLogger().d("machineSet id= " + id + "------------" + e.getMessage());
            }
        }

        @Override
        public void onResponse(String response, int id) {
            try {
//            Toast.makeText(MainActivity.this, "MyStringCallback   -------      onResponse    id=" + id, Toast.LENGTH_LONG).show();
                Gson gson = new Gson();

                if (!TextUtils.isEmpty(response) && response.indexOf("code\":2") != -1) {
                    ErrorData mErrorData = gson.fromJson(response, ErrorData.class);
                    Toast.makeText(MainActivity.this, mErrorData.getResult(), Toast.LENGTH_SHORT).show();

                    return;
                }

                if (id == 1) {
                    LogUtil.getLogger().d3("paiData = " + response);
                    String paiData = CryptUtils.decryptAES(response, Constant.AES_KEY);
                    LogUtil.getLogger().d3("paiData = " + paiData);
                    if (paiData == null)
                        return;
                    LogUtil.getLogger().d3("PokerStatus = " + paiData);
                    LotteryPaiData lotteryPaiData = gson.fromJson(paiData, LotteryPaiData.class);
                    PaiItem paiItem = lotteryPaiData.getResult();

                    if (paiItem.getStatus() == 1) {
                        LogUtil.getLogger().d4("paiData = " + response);
                    } else if (paiItem.getStatus() == 2) {
                        LogUtil.getLogger().d5("paiData = " + response);
                    } else if (paiItem.getStatus() == 4) {
                        LogUtil.getLogger().d6("paiData = " + response);
                    }
                    // 更新界面
                    updateUI(paiItem);
                } else if (id == 3) {
                    LogUtil.getLogger().d7("machineSet", "machineSet = " + response);
                    MachineSetData machineSetData = gson.fromJson(response, MachineSetData.class);
                    if (machineSetData.getCode() == -1) {
//                        Toast.makeText(MainActivity.this, "machineset error", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    machineSet = machineSetData.getResult();
                    if (machineSet == null) {
//                        Toast.makeText(MainActivity.this, "machineset null", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    // 获取台面余额
                    OkHttpUtils.post().url(Constant.GET_MESA_SCORE)
                            .addParams("position", String.valueOf(Constant.POSITION))
                            .addParams(Constant.KEY_MACHINE_ID, Constant.MACHINE_ID).id(5)
                            .build().execute(new MyStringCallback());
                } else if (id == 5) {
                    LogUtil.getLogger().d("MeasureData = " + response);
//                    Toast.makeText(MainActivity.this, "measuredata resp:" + response, Toast.LENGTH_SHORT).show();
                    MesaScoreData mesaScoreData = gson.fromJson(response, MesaScoreData.class);
                    if (mesaScoreData == null) {
//                        Toast.makeText(MainActivity.this, "measuredata null", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (mesaScoreData.getCode() == -1) {
//                        Toast.makeText(MainActivity.this, "measure error", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    MesaScoreItem item = mesaScoreData.getResult();
                    if (item != null) {
                        int balance = (int) item.getMesaScore();
                        mBetPanel.setBalance(balance);
                        // 设置主界面
                        resetView();
                    } else {
//                        Toast.makeText(MainActivity.this, "measure error:" + mesaScoreData.toString(), Toast.LENGTH_SHORT).show();
                    }
                } else if (id == 6) {
//                Toast.makeText(MainActivity.this, "response:" + response, Toast.LENGTH_SHORT).show();
                    String history = CryptUtils.decryptAES(response, Constant.AES_KEY);
                    LogUtil.getLogger().d("history = " + history);
//                Toast.makeText(MainActivity.this, "history:" + history, Toast.LENGTH_LONG).show();
                    HistoryData historyData = gson.fromJson(history, HistoryData.class);
                    if (historyData.getCode() == -1) {
//                        Toast.makeText(MainActivity.this, "history error", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    HistoryItem historyItem = historyData.getResult();
                    resetView();
                    if (historyItem != null && historyItem.getCurrentPoker() != null)
                        updateUponHistory(historyItem);

                    // 获取机台设置
                    OkHttpUtils.post().url(Constant.GET_MACHINESET_BY_ID)
                            .addParams(Constant.KEY_MACHINE_ID, Constant.MACHINE_ID).id(3).build().execute(new MyStringCallback());
//                    OkHttpUtils.get().url("http://101.200.41.41:82/machine/machineset/getById?machine_id=7cfea17224c84406b7d4b32176242c3e").id(3).build().execute(new MyStringCallback());
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void readConfig() {
        Log.d("MeasureData", "---------------readConfig-----------");
        if (!FileUtils.isFolderExist(DIR)) {
            FileUtils.creatSDDir(DIR);
            if (!FileUtils.isFileExist(DIR, CONFIG)) {
                try {
                    FileUtils.createFileInSDCard(DIR, CONFIG);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
//        Log.d("MeasureData", "---------------readConfig-----ing------");
        byte[] bytes = FileUtils.readFromSD(DIR, CONFIG);
        String config = new String(bytes);
        String[] configs = config.split("\r\n");
//        Log.d("MeasureData", "config = " + config);
//        Log.d("MeasureData", "configs.length = " + configs.length);
        if (configs != null && configs.length > 0) {
            for (int i = 0; i < configs.length; i++) {
//                Log.d("MeasureData", configs[i]);
                String str = configs[i];
                String[] map = str.split("#");
                if (map != null && map.length == 2) {
                    if (map[0].equals("MACHINE_ID")) {
//                        mBetPanel.setMachinePos(Integer.parseInt(map[1]));
//                        mBetPanel.setMachinePos(1);
//                        Constant.POSITION = Integer.parseInt(map[1]);
                        Constant.MACHINE_ID = map[1];
//                        Log.d("MeasureData", "map[0]=" + map[0] + "-------map[1]=" + map[1]);
                    } else if (map[0].equals("POSITION")) {
//                        Log.d("MeasureData", "map[0]=" + map[0] + "-------map[1]=" + map[1]);
                        try {
                            Constant.POSITION = Integer.parseInt(map[1]);
                            mBetPanel.setMachinePos(Constant.POSITION);
                        } catch (Exception e) {
                            mBetPanel.setMachinePos(9);
                        }
                    }
                }
            }
        }

//        Constant.MACHINE_ID = "7cfea17224c84406b7d4b32176242c3e";
//        Constant.POSITION = 3;
//        mBetPanel.setMachinePos(Constant.POSITION);
    }

    private void initIfly() {
        if (SpeechSynthesizer.getSynthesizer() != null) {
            LogUtil.getLogger().d("soundutils", "initIfly------！=null-----------");
            mTts = SpeechSynthesizer.getSynthesizer();
        } else {
            LogUtil.getLogger().d("soundutils", "initIfly-----------------");
            mTts = SpeechSynthesizer.createSynthesizer(this, mTtsInitListener);
        }
    }

    //qiniu play
    private void playIfly(String text) {

        LogUtil.getLogger().d("soundutils", "-text-" + text);
        if (mTts == null) {
            LogUtil.getLogger().d("08201216", "-mTts == null------无法播报---------");
            initIfly();
            return;
        } else {
            LogUtil.getLogger().d("08201216", "-mTts != null------执行播报---------");
        }

        // 移动数据分析，收集开始合成事件
        FlowerCollector.onEvent(this, "tts_play");
        // 1.创建 SpeechSynthesizer 对象, 第二个参数:本地合成时传 InitListener
        LogUtil.getLogger().d("soundutils", "-------------generateAudio-------------------");
        LogUtil.getLogger().d("soundutils", "mTts == null----" + (mTts == null));
        mTts.setParameter(SpeechConstant.PARAMS, null);
        mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);// 设置云端
        mTts.setParameter(SpeechConstant.VOICE_NAME, "xiaoyan");          // 设置在线合成发音人
        mTts.setParameter(SpeechConstant.SPEED, "50");       //设置合成语速
        mTts.setParameter(SpeechConstant.PITCH, "50");           //设置合成音调
        mTts.setParameter(SpeechConstant.VOLUME, "100");      //设置合成音量
        mTts.setParameter(SpeechConstant.STREAM_TYPE, "3");         //设置播放器音频流类型
        mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true"); // 设置播放合成音频打断音乐播放，默认为true

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mTts.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/waves/ppp.wav");

        //3.开始合成
        mTts.startSpeaking(text, mSynListener);
        LogUtil.getLogger().d("soundutils", "-------------generateAudio------------2-------");

    }


    // 合成监听器
    private SynthesizerListener mSynListener = new SynthesizerListener() {

        // 会话结束回调接口,没有错误时,error为null
        public void onCompleted(SpeechError error) {
            if (error == null) {
                LogUtil.getLogger().d("08201216", "----------播报成功---------------");
            } else {
                LogUtil.getLogger().d("08201216", "----------播报失败----------------");
                LogUtil.getLogger().d("08201216", error.getMessage());
            }
            LogUtil.getLogger().d("08201216", error.getMessage());
            error.printStackTrace();
        }

        // 缓冲进度回调
        // //percent为缓冲进度0~100,beginPos为缓冲音频在文本中开始位置,endPos表示缓冲音频在文本中结束位置,info为附加信息。
        public void onBufferProgress(int percent, int beginPos, int endPos, String info) {
            LogUtil.getLogger().d("soundutils", "---------------onBufferProgress-----------------");
        }

        // 开始播放
        public void onSpeakBegin() {
            LogUtil.getLogger().d("soundutils", "--------------onSpeakBegin------------------");
        }

        // 暂停播放
        public void onSpeakPaused() {
            LogUtil.getLogger().d("soundutils", "--------------onSpeakPaused------------------");
        }

        // 播放进度回调
        // //percent为播放进度0~100,beginPos为播放音频在文本中开始位置,endPos表示播放音频在文本中结束位置.
        public void onSpeakProgress(int percent, int beginPos, int endPos) {
            LogUtil.getLogger().d("soundutils", "--------------------onSpeakProgress------------");
        } // 恢复播放回调接口

        public void onSpeakResumed() {
            LogUtil.getLogger().d("soundutils", "-----------------onSpeakResumed---------------");
        }

        // 会话事件回调接口
        public void onEvent(int arg0, int arg1, int arg2, Bundle arg3) {
            LogUtil.getLogger().d("soundutils", "--------------onEvent------------------");
        }
    };

    /**
     * 初始化监听。
     */
    private InitListener mTtsInitListener = new InitListener() {
        @Override
        public void onInit(int code) {
            LogUtil.getLogger().d("soundutils", "InitListener init() code = " + code);
            if (code != ErrorCode.SUCCESS) {
                LogUtil.getLogger().d("soundutils", "初始化失败,错误码：" + code);
            } else {

                LogUtil.getLogger().d("soundutils", "初始化成功" + code);
                // 初始化成功，之后可以调用startSpeaking方法
                // 注：有的开发者在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成，
                // 正确的做法是将onCreate中的startSpeaking调用移至这里
            }
        }
    };
}
